﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Linq;

namespace Bing
{
    /// <summary>
    /// Contains an array of results returned for a request that specifies the Translation <see cref="ApiHelper.SourceType"/>.
    /// </summary>
    [DebuggerDisplay("Total={Total}, Results={Results.Count}, Errors={Errors.Count}")]
    public class TranslationResponse: SearchResponseBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TranslationResponse"/> class.
        /// </summary>
        public TranslationResponse(XContainer element): base(element)
        {
            TranslationResults = new List<TranslationResult>();
        }

        /// <summary>
        /// Returns an array of <see cref="TranslationResult"/> objects.
        /// </summary>
        /// <value>Returns an array of <see cref="TranslationResult"/> objects.</value>
        public List<TranslationResult> TranslationResults { get; set; }

        /// <summary>
        /// Parses the response from the Bing API.
        /// </summary>
        /// <param name="element">The XML from the Bing API</param>
        /// <returns>An <see cref="TranslationResponse" /></returns>
        public static TranslationResponse ParseElement(XContainer element)
        {
            TranslationResponse translationResponse = new TranslationResponse(element);
            if (translationResponse.Errors.Count > 0) return translationResponse;

            var translation = element.Element(XName.Get("Translation", ApiHelper.TranslationNs));
            if (translation == null) return translationResponse;

            XElement translationResults = translation.Element(XName.Get("Results", ApiHelper.TranslationNs));
            if (translationResults == null) return translationResponse;
            foreach (XElement result in translationResults.Elements(XName.Get("TranslationResult", ApiHelper.TranslationNs)))
            {
                string value = ApiHelper.GetElementValueOrDefault<string>(result, "TranslatedTerm",
                                                                          ApiHelper.TranslationNs);
                translationResponse.TranslationResults.Add(new TranslationResult { TranslatedTerm = value });
            }

            return translationResponse;
        }
    }
}
